<template>
  <div class="register-container">
    <!-- 返回首页按钮和主题切换 -->
    <div class="back-home">
      <el-button 
        text 
        @click="$router.push('/')"
        class="back-btn"
      >
        <el-icon><ArrowLeft /></el-icon>
        {{ $t('common.home') }}
      </el-button>
      <ThemeToggle />
    </div>

    

    <div class="register-content">
      <div class="register-left">
        <div class="brand-section">
          <h1 class="brand-title">{{ $t('auth.brand.title') }}</h1>
          <p class="brand-subtitle">{{ $t('auth.brand.registerSubtitle') }}</p>
          <div class="feature-highlights">
            <div class="highlight-item">
              <div class="highlight-icon">🎭</div>
              <div class="highlight-content">
                <h4>{{ $t('auth.brand.features.richCharacters') }}</h4>
                <p>{{ $t('auth.brand.features.richCharactersDesc') }}</p>
              </div>
            </div>
            <div class="highlight-item">
              <div class="highlight-icon">🎙️</div>
              <div class="highlight-content">
                <h4>{{ $t('auth.brand.features.voiceInteraction') }}</h4>
                <p>{{ $t('auth.brand.features.voiceInteractionDesc') }}</p>
              </div>
            </div>
            <div class="highlight-item">
              <div class="highlight-icon">🤖</div>
              <div class="highlight-content">
                <h4>{{ $t('auth.brand.features.intelligentAI') }}</h4>
                <p>{{ $t('auth.brand.features.intelligentAIDesc') }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="register-right">
        <div class="register-box">
          <div class="register-header">
            <h2>{{ $t('auth.register.title') }}</h2>
            <p>{{ $t('auth.register.subtitle') }}</p>
          </div>
          
          <el-form
            ref="registerFormRef"
            :model="registerForm"
            :rules="registerRules"
            class="register-form"
            size="large"
            @submit.prevent="handleRegister"
          >
            <el-form-item prop="username">
              <el-input
                v-model="registerForm.username"
                :placeholder="$t('auth.register.username')"
                prefix-icon="User"
                clearable
              />
            </el-form-item>
            
            <el-form-item prop="email">
              <el-input
                v-model="registerForm.email"
                :placeholder="$t('auth.register.email')"
                prefix-icon="Message"
                clearable
              />
            </el-form-item>
            
            <el-form-item prop="nickname">
              <el-input
                v-model="registerForm.nickname"
                :placeholder="$t('auth.register.nickname')"
                prefix-icon="Avatar"
                clearable
              />
            </el-form-item>
            
            <el-form-item prop="password">
              <el-input
                v-model="registerForm.password"
                type="password"
                :placeholder="$t('auth.register.password')"
                prefix-icon="Lock"
                show-password
                clearable
              />
            </el-form-item>
            
            <el-form-item prop="confirmPassword">
              <el-input
                v-model="registerForm.confirmPassword"
                type="password"
                :placeholder="$t('auth.register.confirmPassword')"
                prefix-icon="Lock"
                show-password
                clearable
                @keyup.enter="handleRegister"
              />
            </el-form-item>
            
            <el-form-item prop="captcha">
              <div class="captcha-row">
                <el-input
                  v-model="registerForm.captcha"
                  :placeholder="$t('auth.register.captcha')"
                  :disabled="loading"
                  clearable
                  @keyup.enter="handleRegister"
                  style="flex: 1"
                >
                  <template #prefix>
                    <el-icon><Key /></el-icon>
                  </template>
                </el-input>
                <Captcha 
                  ref="captchaRef"
                  @change="handleCaptchaChange"
                  :width="120"
                  :height="40"
                />
              </div>
            </el-form-item>
            
            <el-form-item>
              <el-checkbox v-model="agreeTerms" class="agree-terms">
                {{ $t('auth.register.agreeTerms') }}
                <a href="/terms" target="_blank">{{ $t('auth.register.userAgreement') }}</a>
                和
                <a href="/privacy" target="_blank">{{ $t('auth.register.privacyPolicy') }}</a>
              </el-checkbox>
            </el-form-item>
            
            <el-form-item>
              <el-button
                type="primary"
                class="register-btn"
                :loading="loading"
                :disabled="loading || !agreeTerms"
                @click="handleRegister"
              >
                <el-icon v-if="!loading"><UserFilled /></el-icon>
                {{ loading ? $t('auth.register.registering') : $t('auth.register.registerButton') }}
              </el-button>
            </el-form-item>
            
            <el-form-item>
              <div class="login-link">
                {{ $t('auth.register.hasAccount') }}
                <router-link to="/login">{{ $t('auth.register.loginNow') }}</router-link>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { ElForm, ElMessage } from 'element-plus'
import { User, Message, Avatar, Lock, Key, UserFilled, ArrowLeft, ArrowDown } from '@element-plus/icons-vue'
import { useUserStore } from '../../store/modules/user'
import type { UserRegister } from '../../types/user'
import { defineAsyncComponent } from 'vue'
import { setLocale, getCurrentLocale, type SupportedLocale } from '../../i18n'
import ThemeToggle from '../../components/common/ThemeToggle.vue'

const Captcha = defineAsyncComponent(() => import('../../components/Captcha.vue'))


const router = useRouter()
const userStore = useUserStore()
const { t } = useI18n()

const registerFormRef = ref<InstanceType<typeof ElForm>>()
const captchaRef = ref()
const loading = ref(false)
const agreeTerms = ref(false)
const currentCaptcha = ref('')
const currentLanguage = ref<SupportedLocale>(getCurrentLocale())

// 注册表单数据
const registerForm = reactive<UserRegister & { confirmPassword: string; captcha: string }>({
  username: '',
  email: '',
  password: '',
  nickname: '',
  confirmPassword: '',
  captcha: ''
})

// 验证确认密码
const validateConfirmPassword = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error(t('auth.validation.confirmPasswordRequired')))
  } else if (value !== registerForm.password) {
    callback(new Error(t('auth.validation.passwordMismatch')))
  } else {
    callback()
  }
}

// 验证邮箱格式
const validateEmail = (rule: any, value: string, callback: any) => {
  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
  if (value === '') {
    callback(new Error(t('auth.validation.emailRequired')))
  } else if (!emailRegex.test(value)) {
    callback(new Error(t('auth.validation.emailInvalid')))
  } else {
    callback()
  }
}

// 表单验证规则
const registerRules = {
  username: [
    { required: true, message: t('auth.validation.usernameRequired'), trigger: 'blur' },
    { min: 3, max: 50, message: t('auth.validation.usernameLength'), trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: t('auth.validation.usernameInvalid'), trigger: 'blur' }
  ],
  email: [
    { required: true, validator: validateEmail, trigger: 'blur' }
  ],
  password: [
    { required: true, message: t('auth.validation.passwordRequired'), trigger: 'blur' },
    { min: 6, max: 50, message: t('auth.validation.passwordLength'), trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validateConfirmPassword, trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: t('auth.validation.captchaRequired'), trigger: 'blur' },
    { len: 4, message: t('auth.validation.captchaLength'), trigger: 'blur' }
  ]
}

const handleCaptchaChange = (code: string) => {
  currentCaptcha.value = code
}

const refreshCaptchaAndClear = () => {
  if (captchaRef.value) {
    captchaRef.value.refresh()
  }
  registerForm.captcha = ''
}

const handleLanguageChange = (locale: SupportedLocale) => {
  currentLanguage.value = locale
  setLocale(locale)
}

const clearForm = () => {
  registerForm.username = ''
  registerForm.email = ''
  registerForm.password = ''
  registerForm.confirmPassword = ''
  registerForm.captcha = ''
}

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  try {
    const valid = await registerFormRef.value.validate()
    if (!valid) return
    
    if (!agreeTerms.value) {
      ElMessage.warning(t('auth.register.agreeTermsRequired'))
      return
    }
    
    // 验证验证码
    if (!captchaRef.value?.validate(registerForm.captcha)) {
      ElMessage.error(t('auth.login.captchaError'))
      refreshCaptchaAndClear()
      return
    }
    
    loading.value = true
    await userStore.register(registerForm)
    
    ElMessage.success(t('auth.register.registerSuccess'))
    router.push('/login')
    
  } catch (error: any) {
    console.error('Register failed:', error)
    
    // 注册失败，清空表单并刷新验证码
    clearForm()
    refreshCaptchaAndClear()
    
    ElMessage.error({
      message: t('auth.register.registerFailed'),
      duration: 4000,
      showClose: true
    })
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.back-home {
  position: absolute;
  top: 20px;
  left: 20px;
  right: 20px;
  z-index: 10;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.back-btn {
  color: white;
  font-size: 16px;
  padding: 8px 16px;
}

.back-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
}

.register-content {
  max-width: 1100px;
  width: 100%;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 60px;
  align-items: center;
}

.register-left {
  color: white;
  padding: 40px;
}

.brand-section {
  text-align: left;
}

.brand-title {
  font-size: 48px;
  font-weight: 700;
  margin-bottom: 16px;
  background: linear-gradient(45deg, #fff, #e2e8f0);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.brand-subtitle {
  font-size: 20px;
  opacity: 0.9;
  margin-bottom: 40px;
  line-height: 1.6;
}

.feature-highlights {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.highlight-item {
  display: flex;
  align-items: flex-start;
  gap: 20px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.highlight-icon {
  font-size: 28px;
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  flex-shrink: 0;
}

.highlight-content h4 {
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 8px 0;
}

.highlight-content p {
  font-size: 14px;
  margin: 0;
  opacity: 0.8;
  line-height: 1.5;
}

.register-right {
  display: flex;
  justify-content: center;
}

.register-box {
  background: white;
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 450px;
}

.register-header {
  text-align: center;
  margin-bottom: 32px;
}

.register-header h2 {
  font-size: 28px;
  font-weight: 700;
  color: #1a202c;
  margin-bottom: 8px;
}

.register-header p {
  color: #64748b;
  font-size: 16px;
}

.register-form {
  width: 100%;
}

.register-form :deep(.el-form-item) {
  margin-bottom: 18px;
}

.register-form :deep(.el-input__wrapper) {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #e2e8f0;
  padding: 12px 16px;
  height: 48px;
}

.register-form :deep(.el-input__wrapper:hover) {
  border-color: #667eea;
}

.register-form :deep(.el-input__wrapper.is-focus) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.captcha-row {
  display: flex;
  gap: 12px;
  align-items: center;
}

.agree-terms {
  font-size: 14px;
  color: #64748b;
  line-height: 1.6;
}

.agree-terms a {
  color: #667eea;
  text-decoration: none;
  margin: 0 2px;
}

.agree-terms a:hover {
  text-decoration: underline;
}

.register-btn {
  width: 100%;
  height: 48px;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  transition: all 0.3s ease;
}

.register-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

.register-btn:disabled {
  opacity: 0.6;
  transform: none;
  box-shadow: none;
}

.login-link {
  text-align: center;
  color: #64748b;
  font-size: 14px;
}

.login-link a {
  color: #667eea;
  text-decoration: none;
  font-weight: 500;
  margin-left: 4px;
}

.login-link a:hover {
  text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .register-content {
    grid-template-columns: 1fr;
    gap: 40px;
    max-width: 450px;
  }
  
  .register-left {
    text-align: center;
    padding: 20px;
  }
  
  .brand-title {
    font-size: 36px;
  }
  
  .feature-highlights {
    display: none;
  }
  
  .register-box {
    padding: 30px 20px;
  }
}

@media (max-width: 480px) {
  .register-container {
    padding: 10px;
  }
  
  .register-box {
    padding: 24px 16px;
  }
  
  .register-header h2 {
    font-size: 24px;
  }
}

/* 深色模式样式 */
:global(.dark) .register-container {
  background: linear-gradient(135deg, #1e1b4b 0%, #312e81 100%) !important;
}

:global(.dark .register-box) {
  background: var(--surface) !important;
  border-color: var(--border) !important;
}

:global(.dark .register-header h2) {
  color: var(--text-primary) !important;
}

:global(.dark .register-header p) {
  color: var(--text-secondary) !important;
}

:global(.dark .brand-title) {
  color: var(--text-primary) !important;
}

:global(.dark .brand-subtitle) {
  color: var(--text-secondary) !important;
}

:global(.dark .highlight-item h4) {
  color: var(--text-primary) !important;
}

:global(.dark .highlight-item p) {
  color: var(--text-secondary) !important;
}

:global(.dark .back-btn) {
  color: var(--text-primary) !important;
}

:global(.dark .back-btn:hover) {
  background: rgba(255, 255, 255, 0.1) !important;
}

:global(.dark .register-footer-links .el-link) {
  color: var(--text-secondary) !important;
}

:global(.dark .register-footer-links .el-link:hover) {
  color: var(--primary-color) !important;
}
</style> 